package com.yanheng.springbootjdbcTemplate.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.yanheng.springbootjdbcTemplate.domain.User;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public void saveUser(User user) {
		jdbcTemplate.update("insert into users() values(?, ?, ?, ?, ?)",user.getId(), user.getUserName(), user.getPassWord(), user.getUserSex(), user.getNickName());
	}

	@Override
	public void updateUser(Long id, User user) {
		jdbcTemplate.update("update users set userName=?, password=?, user_sex=?, nick_name=? where id=?", user.getUserName(),user.getPassWord(), user.getUserSex(), user.getNickName(), id);
	}

	@Override
	public User getUser(Long id) {
		User user = jdbcTemplate.queryForObject("select * from users where id="+id, new BeanPropertyRowMapper<User>(User.class));
		return user;
	}

	@Override
	public void deleteUserById(Long id) {
		jdbcTemplate.update("delete from users where id="+id);
	}

	@Override
	public List<User> getAllUsers() {
		return jdbcTemplate.query("select id, userName, password, user_sex, nick_name from users", new BeanPropertyRowMapper<User>(User.class));
	}

	@Override
	public void deleteAllUsers() {
		jdbcTemplate.update("delete from users");
	}

}
